package com.springcloud.sc.ucpv5.client.common.ini;

/* 
 * @(#) IniReader.java 
 * Created on 2004-10-14 
 * Created by James Fancy 
 */

import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Properties;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * @author James Fancy
 */
public class IniReader {
	// 当前属性值
	protected HashMap<String, Properties> sections = new HashMap<String, Properties>();

	private String fileName = null;

	public IniReader() {
		;
	}

	public IniReader(String fileName) {
		this.fileName = fileName;
		sections = readFile(fileName);
		if (sections == null) {
			sections = new HashMap<String, Properties>();
		}
	}

	private HashMap<String, Properties> readFile(String fileName) {
		FileReader FReadFile = null;
		BufferedReader BReadFile = null;

		HashMap<String, Properties> sections = null;

		File f = new File(fileName);
		try {
			// 判断文件是否存在
			if (f.exists()) {
				InputStream inputStream = new FileInputStream(f);
				InputStreamReader inputStreamReader = new InputStreamReader(inputStream, "UTF-8");
				BReadFile = new BufferedReader(inputStreamReader);
				// 读取文件
				sections = read(BReadFile);
			} else {
				;
			}
		} catch (Exception e) {
			e.printStackTrace();
		}

		finally {
			try {
				if (BReadFile != null)
					BReadFile.close();
				if (FReadFile != null)
					FReadFile.close();
			} catch (Exception e) {
				e.printStackTrace();
			}
		}

		return sections;
	}

	protected HashMap<String, Properties> read(BufferedReader reader) throws IOException {

		HashMap<String, Properties> sections = new HashMap<String, Properties>();

		String currentSecion = ""; // 当前工作secion
		String line;
		while ((line = reader.readLine()) != null) {
			String tmp = parseLine(line, currentSecion, sections);
			if (tmp != null) {
				currentSecion = tmp;
			}
		}

		return sections;
	}

	protected String parseLine(String line, String currentSecion, HashMap<String, Properties> sections) {
		try {
			line = line.trim();
			if (line.matches("\\[.*\\]")) {
				currentSecion = line.replaceFirst("\\[(.*)\\]", "$1");
				Properties current = new Properties();

				if (current != null) {
					sections.put(currentSecion, current);
				}
			} else if (line.matches(".*=.*")) {
				int i = line.indexOf('=');
				String name = line.substring(0, i);
				String value = line.substring(i + 1);
				// 存储
				sections.get(currentSecion).setProperty(name.trim(), value.trim());
			} else {
				// 非有效行
				return null;
			}

		} catch (Exception e) {
			// TODO: handle exception
			e.printStackTrace();
		}

		return currentSecion;
	}

	public String getValue(String section, String name) {
		Properties p = (Properties) sections.get(section);

		if (p == null) {
			return null;
		}

		String value = p.getProperty(name);
		return value;
	}

	public void setValue(String section, String variable, String value) {
		setItemValue(section, variable, value);

		// 写配置文件
		try {
			writeToFile();
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}

	// 设置定义值, 但是不需要进行文件保存, 统一保存处理
	public void setItemValue(String section, String variable, String value) {
		{
			Object o = sections.get(section);
			Properties p = null;
			if (o == null) {
				p = new Properties();
				sections.put(section, p);
			} else {
				p = (Properties) o;
			}
			p.setProperty(variable, value);
		}
	}

	public void writeToFile() {
		StringBuffer fileContent = new StringBuffer();
		for (String section : sections.keySet()) {
			fileContent.append("[");
			fileContent.append(section);
			fileContent.append("]");
			fileContent.append("\n");

			Properties p = sections.get(section);
			for (Object key : p.keySet()) {
				fileContent.append(key.toString());
				fileContent.append("=");
				fileContent.append(p.get(key).toString());
				fileContent.append("\n");
			}
			fileContent.append("\n");
		}
		try {
			File file = new File(fileName);
			if (!file.exists()) {
				file.createNewFile();
			}
			FileOutputStream writerStream = new FileOutputStream(file);
			BufferedWriter bufferedWriter = new BufferedWriter(new OutputStreamWriter(writerStream, "UTF-8"));
			bufferedWriter.write(fileContent.toString());
			bufferedWriter.flush();
			bufferedWriter.close();

		} catch (Exception e) {
			// TODO: handle exception
			e.printStackTrace();
		}
	}

	/**
	 * 修改ini配置文件中变量的值
	 * 
	 * @param file
	 *            配置文件的路径
	 * @param section
	 *            要修改的变量所在段名称
	 * @param variable
	 *            要修改的变量名称
	 * @param value
	 *            变量的新值
	 * @throws IOException
	 *             抛出文件操作可能出现的io异常
	 */
	public static boolean setProfileString(String file, String section, String variable, String value) throws IOException {
		String fileContent, allLine, strLine, newLine, remarkStr;
		String getValue = null;
		File tmpFile = new File(file);
		if (!tmpFile.exists()) {
			tmpFile.createNewFile();
		}

		InputStream inputStream = new FileInputStream(tmpFile);
		InputStreamReader inputStreamReader = new InputStreamReader(inputStream, "UTF-8");
		BufferedReader bufferedReader = new BufferedReader(inputStreamReader);

		// 是否存在[]的定义
		boolean isInSection = false;

		// 表示是否已经判断处理完毕
		boolean isInSection_finish = false;

		fileContent = "";

		try {
			while ((allLine = bufferedReader.readLine()) != null) {
				allLine = allLine.trim();
				if (!isInSection_finish) {
					if (allLine.split("[;]").length > 1) {
						remarkStr = ";" + allLine.split(";")[1];
					} else {
						remarkStr = "";
					}

					strLine = allLine;

					Pattern p;
					Matcher m;
					p = Pattern.compile("\\[\\s*.*\\s*\\]");
					m = p.matcher((strLine));
					if (m.matches()) {
						p = Pattern.compile("\\[\\s*" + section + "\\s*\\]");
						m = p.matcher(strLine);
						if (m.matches()) {
							isInSection = true;
						} else {
							if (isInSection) {
								// 前一次找到, 但是现在在出现在另外一处了, 那么将值写入该行之前就好 20170615
								// 伍尚源
								newLine = variable + " = " + value + " ";
								fileContent += newLine + "\r\n";

								isInSection_finish = true;
							}
						}
					}

					if (isInSection == true) {
						if (variable.equals("FtpIP")) {
							System.out.println("");
						}
						// 判断该项是否注释掉, 用";"来注释
						if (strLine.indexOf(";") >= 0) {
							// 去掉注释
							strLine = strLine.replaceAll(";", "");
						}

						strLine = strLine.trim();
						String[] strArray = strLine.split("=");
						getValue = strArray[0].trim();
						if (getValue.equalsIgnoreCase(variable)) {
							newLine = getValue + " = " + value + "";
							fileContent += newLine + "\r\n";
							isInSection_finish = true;
							continue;
						}
					}
				}
				fileContent += allLine + "\r\n";
			}

			if (!isInSection) {
				// 连[] 内容都没有找到, 新加入一个
				newLine = "[" + section + "]";
				fileContent += newLine + "\r\n";

				newLine = variable + " = " + value + " ";
				fileContent += newLine + "\r\n";
			} else if (!isInSection_finish) {
				// 出现在最后找到[] , 但是变量未定义
				newLine = variable + " = " + value + " ";
				fileContent += newLine + "\r\n";
			}

			// 写文件
			BufferedWriter bufferedWriter = new BufferedWriter(new FileWriter(file, false));
			bufferedWriter.write(fileContent);
			bufferedWriter.flush();
			bufferedWriter.close();
		} catch (IOException ex) {
			throw ex;
		} finally {
			bufferedReader.close();
		}
		return false;
	}

	public Properties getSection(String section) {
		Properties p = (Properties) sections.get(section);
		if (p == null) {
			return null;
		}
		return p;
	}

	public void setSection(String section) {
		Properties current = new Properties();
		if (current != null) {
			sections.put(section, current);
		}
	}

	public void removeSection(String section) {
		sections.remove(section);
	}

	public List<String> getSectionList() {
		if (this.sections.size() <= 0) {
			return null;
		}
		List<String> sectionList = new ArrayList<String>();
		for (String section : this.sections.keySet()) {
			sectionList.add(section);
		}

		return sectionList;
	}

	public IniReader copy() {
		IniReader reader = new IniReader();
		for (String section : sections.keySet()) {
			Properties p = sections.get(section);
			if (p == null) {
				for (Object o : p.keySet()) {
					try {
						String tmp = o.toString();
						reader.setItemValue(section, tmp, p.getProperty(tmp));
					} catch (Exception e) {
						e.printStackTrace();
					}
				}
			}
		}
		return reader;
	}

}
